package com.kuizii.base.common.idgenerator;


import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: nuanyang
 * @Date: 2019/8/22 0022 15:12
 */
public class SnowFlakeGenerator extends   NodeDistribute  implements IdGenerator<Long> {

    private final long startTimeMillis = 1567418727663L;

    /**
     * 时间戳点位 2^41/365*24*60*60*1000*1000 如果以每毫秒产生不同ID算 41位可以支持69年
     */
    private final int timestampBits = 41;

    /**
     * 正负标志位
     */
    private final int signBits = 1;
    /**
     * 节点数 2^8 可以有256个节点
     */
    private final int nodeBit = 8;

    /**
     * 在计算机计算性能允许的情况下,支持每毫秒生成2^10个Id,即每秒12 040 000个自增数
     */
    private final int sequenceBit = 10;


    private long lastMillis = 0L;

    private final AtomicLong sequence = new AtomicLong(0L);

    private long nodeId = 0;


    @Override
    public Long newId() {

        if (System.currentTimeMillis() == lastMillis) {
            sequence.incrementAndGet();
        } else {
            lastMillis = System.currentTimeMillis();
            sequence.set(0L);

        }

        return (lastMillis - startTimeMillis) << (nodeBit + sequenceBit) | nodeId << sequenceBit | sequence.get();
    }


}
